import React,{ Component,Fragment } from 'react';
import {
	StyleSheet,
	View,
	Text,
	TouchableOpacity
} from 'react-native';

export default class CheckList extends Component{
	constructor(props){
		super(props);
		this.selectobj = {}; //标记是否被选择的对象
		this.checkData = []; //checkbox返回的数据
		this.initState();
	}
	
	initState = ()=>{
		const obj={};
		this.props.data.map((item,index)=>{
			if(index===0){
				obj[`check${index}`] = true;
				if(this.props.type === 'checkbox'){
					this.checkData.push(item.value)
				}
			}else{
				obj[`check${index}`] = false;
			}
			
		})
		this.selectobj = obj;
	}

	checkClick = (item,index)=>{
		if(this.props.type === 'radio'){
			for(let key in this.selectobj){
				this.selectobj[key] = false;
			}
			this.selectobj[`check${index}`]=true;
			this.setState(this.selectobj);
			this.props.checkClick(item)
		}else{
			if(this.selectobj[`check${index}`]){
				let index=this.checkData.indexOf(item.value);
				this.checkData.splice(index,1);
			}else{
				this.checkData.push(item.value)
			}

			this.selectobj[`check${index}`]=!this.selectobj[`check${index}`];
			this.setState(this.selectobj);

			

			this.props.checkClick(this.checkData)
		}
		
		
	}

	initRadio = ()=>{
		return this.props.data.map((item,index)=>{
			return  <TouchableOpacity
						key={item.value}
						onPress={()=>this.checkClick(item,index)}
					>
						{this.selectobj[`check${index}`]?
							<Text style={[styles.policyItem,styles.policyItemSelected]}>{item.name}</Text>
							:
							<Text style={styles.policyItem}>{item.name}</Text>
						}
					</TouchableOpacity>
		})
	}
	render(){
		return <Fragment>
			{this.initRadio()}
		</Fragment>
	}
}

const styles=StyleSheet.create({
	policyItem:{
		paddingTop:5,
		paddingRight:10,
		paddingBottom:5,
		paddingLeft:10,
		borderWidth:1,
		borderColor:'#ccc',
		color:'#ccc',
		borderRadius:14,
		marginBottom:10,
		marginLeft:5,
		marginRight:5
	},
	policyItemSelected:{
		borderColor:'#f54545',
		color:'#f54545'
	}
})